﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kooboo.Commerce
{
    class TaxContext
    {
        public TaxContext()
        {
            this.Items = new List<TaxItem>();
        }

    

        public List<TaxItem> Items
        {
            get;
            set;
        }

        public string Country
        {
            get;
            set;
        }

        public string State
        {
            get;
            set;
        }

        public void Execute()
        {
            foreach (var item in this.Items)
            {
                var tax = item.Product.Tax;
                if (tax == null)
                {
                    continue;
                }
                else
                {
                    var locals = tax.SubTaxes.Where(i => i.Country.CountryName== item.Country).ToArray();

                    if (locals.Length>0)
                    {
                        var local = locals.Where(i => i.State == item.State).FirstOrDefault();//match country and state
                        if (local == null)
                        {
                            local = locals.Where(i => i.State == "").FirstOrDefault();//match country and state is empty
                            if (local == null)//can NOT find an exact tax rule, so assign percent with the parent tax.
                            {
                                item.TaxPercent = tax.Percent;
                            }
                            else
                            {
                                item.TaxPercent = local.Percent;
                            }
                        }
                        else
                        {
                            item.TaxPercent = local.Percent;
                        }
                    }
                    else
                    {
                        item.TaxPercent = tax.Percent;
                    }

                }
            }
        }
    }

    class TaxItem
    {
        public IProduct Product
        {
            get;
            set;
        }

        public decimal TaxPercent
        {
            get;
            set;
        }

        public string Country
        {
            get;
            set;
        }

        public string State
        {
            get;
            set;
        }

        public object RelatedObject
        {
            get;
            set;
        }
    }
}
